package system

import (
	"context"
	"strconv"
	"time"

	"portal/internal/common"
	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddRoleLogic struct {
	logx.Logger
	ctx       context.Context
	svcCtx    *svc.ServiceContext
	menuModel model.SysMenuModel
	roleModel model.SysRoleModel
	deptModel model.SysDeptModel
}

func NewAddRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddRoleLogic {
	return &AddRoleLogic{
		Logger:    logx.WithContext(ctx),
		ctx:       ctx,
		svcCtx:    svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
		roleModel: model.NewSysRoleModel(svcCtx.Orm),
		deptModel: model.NewSysDeptModel(svcCtx.Orm),
	}
}

func (l *AddRoleLogic) AddRole(req *types.AddRoleRequest) (resp *types.CommonResponse, err error) {
	err = auth.HasPermission(l.menuModel, l.ctx, "system:role:add")
	if err != nil {
		return nil, errorx.Unauthorized
	}
	authinfo, err := auth.GetAuth(l.ctx)
	if err != nil {
		return nil, errorx.AuthNoFound
	}
	roles,_ := auth.GetRoles(l.ctx)
	deptId,_ := strconv.Atoi(authinfo.DeptId)
	// 判断是否拥有所有权限然后进行赋值
	isAdmin ,_ := auth.IsAdmin(l.ctx)
	if !isAdmin {
		if req.DataScope == common.AUTO_SCOPE {
			if req.DeptIds != nil && len(req.DeptIds) > 0 {
				// 校验所选部门是否都有权限
				depts,err := getDepts(l.ctx,int64(deptId),roles,l.deptModel,&types.ListDeptRequest{})
				if err != nil {
					return nil,errorx.NewBizError(500,"部门信息查询失败")
				}
				for _,val := range req.DeptIds {
					isHas := false
					for _,dept := range depts {
						if dept.DeptId == *val {
							isHas = true
						}
					}
					if !isHas {
						return nil,errorx.Unauthorized
					}
				}
			}
		}else if req.DataScope == common.ALL_SCOPE || req.DataScope == common.ONLY_DEPT_SCOPE || req.DataScope == common.INCLUDE_LOW_DEPT_SCOPE{
			return nil,errorx.Unauthorized
		}else {
			return nil,errorx.ParamsError
		}
	}

	role := &model.SysRole{}

	if len(req.RoleName) <= 0 {
		return nil,errorx.NewBizError(500,"用户名不能为空")
	}
	role.RoleName = req.RoleName
	if len(req.RoleKey) <= 0 {
		return nil,errorx.NewBizError(500,"角色权限字符不能为空")
	}
	role.RoleKey = req.RoleKey
	if req.RoleSort <= 0 {
		return nil,errorx.NewBizError(500,"角色顺序不能为空")
	}
	role.RoleSort = req.RoleSort
	if len(req.DataScope) > 0 {
		role.DataScope = req.DataScope
	}
	if len(req.Status) > 0 {
		role.Status = req.Status
	}
	role.CreateBy = authinfo.UserName
	role.CreateTime = time.Now().Unix()
	role.UpdateTime = time.Now().Unix()
	role.UpdateBy = authinfo.UserName
	role.DelFlag = common.EXIST_FLAG
	roleId, err := l.roleModel.InsertGetId(l.ctx,nil, role)
	if err != nil {
		return nil, errorx.SqlInsertError
	}
	oprRoleRelations(l.roleModel, l.ctx, roleId, req.DeptIds, req.MenuIds, "insert")
	return &types.CommonResponse{
		Status: 200,
		Msg:    "更新成功",
		Data: types.IdResponse{
			Id: roleId,
		},
	}, err
}
